package com.example.demo.web

import com.example.demo.data.Ingredient
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import com.example.demo.data.Ingredient.Type
import com.example.demo.data.Order
import com.example.demo.data.Taco
import com.example.demo.data.repository.IngredientRepository
import com.example.demo.data.repository.TacoRepository
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.validation.Errors
import org.springframework.web.bind.annotation.*
import java.sql.Date
import java.util.stream.Collectors
import javax.validation.Valid

@Controller
@RequestMapping("/design")
@SessionAttributes("order")
class DesignTacoController @Autowired constructor(
        private val ingredientRepo: IngredientRepository,
        private val designRepo: TacoRepository
) {

    @ModelAttribute(name = "order")
    fun order(): Order {
        return Order(null, Date(System.currentTimeMillis()))
    }

    @ModelAttribute(name = "taco")
    fun taco(): Taco {
        return Taco()
    }

    @PostMapping
    fun processDesign(@Valid taco: Taco, errors: Errors,
                      @ModelAttribute order: Order): String {
        println("taco is $taco")
        if (errors.hasErrors()) {
            return "design"
        }
        val saved = designRepo.save(taco)
        order.addDesign(saved)
        return "redirect:/orders/current";
    }

    @GetMapping
    fun showDesignForm(model: Model): String {
        val ingredients = mutableListOf<Ingredient>()
        ingredientRepo.findAll().forEach {
            ingredients.add(it)
        }
        Type.values().forEach {
            model.addAttribute(it.toString().toLowerCase(), filterByType(ingredients, it))
        }
        return "design"
    }

    private fun filterByType(ingredients: List<Ingredient>, type: Ingredient.Type): List<Ingredient> {
        return ingredients.stream().filter {
            it.type == type
        }.collect(Collectors.toList())
    }
}